package jp.co.sharp.android.parents.kidsguard.activity.profile;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.adamstyrc.cookiecutter.CookieCutterImageView;
import com.adamstyrc.cookiecutter.ImageUtils;

import java.util.Date;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.common.MimamoriBusinessService;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestCodeConstants;
import jp.co.sharp.android.parents.kidsguard.utils.CommonUtils;

/**
 * Created by liuhb on 2019/12/17.
 */

public class ProfileClipActivity extends Activity {

    private final int REQUEST_CODE = 100;
    CookieCutterImageView imageView;
    private Intent mIntent;
    private MimamoriBusinessService mMimamoriBusinessService;
    private boolean mUnReceiver = false;
    private static final String TAG = "TAG";
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    // プログラムロック
    private String mSyncLock = "syncLock";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "ProfileClipActivity_onCreate");
        setContentView(R.layout.activity_profile_clip);

        imageView = (CookieCutterImageView) findViewById(R.id.ivCookieCutter);
        mMimamoriBusinessService = new MimamoriBusinessService(ProfileClipActivity.this,
                (App)getApplication(), new Intent(getIntent()), (NotificationManager)getSystemService(NOTIFICATION_SERVICE));
        openGallery();
    }

    private void openGallery (){
        Log.i(TAG, "ProfileClipActivity_openGallery");
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "ProfileClipActivity_onStart");
        synchronized (mSyncLock) {
            mMimamoriBusinessService.registerReceiver();
            mUnReceiver = false;
            ((App) getApplication()).setAppStatus(Constants.APP_STATUS_INIT);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "ProfileClipActivity_onStop");
        synchronized (mSyncLock) {
            if (!mUnReceiver) {
                if (mPageJumpFlag) {
                    try {
                        mMimamoriBusinessService.unRegisterSystemReceiver();
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                try {
                    mMimamoriBusinessService.unRegisterReceiver();
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                mUnReceiver = true;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "ProfileClipActivity_onDestroy");
        synchronized (mSyncLock) {
            if (!mUnReceiver) {
                if (mPageJumpFlag) {
                    try {
                        mMimamoriBusinessService.unRegisterSystemReceiver();
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                try {
                    mMimamoriBusinessService.unRegisterReceiver();
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                mUnReceiver = true;
            }
        }
    }

    public void saveImage (View view){
        Log.i(TAG, "ProfileClipActivity_saveImage");
        Bitmap bitmap = imageView.getCroppedBitmap();
        Bitmap circularBitmap = ImageUtils.getCircularBitmap(bitmap);

        mIntent = getIntent();
        String kidImageName = mIntent.getStringExtra(Constants.KEY_KID_IMAGE_NAME);
        StringBuilder builder = new StringBuilder();
        builder.append(getFilesDir().getPath().toString());
        builder.append("/");
        builder.append(kidImageName);
        builder.append(String.valueOf((new Date()).getTime()));
        builder.append(".png");

        String imageUrl = CommonUtils.saveMyBitmap(builder.toString(), circularBitmap);
        mIntent.putExtra(Constants.KEY_KID_IMAGE_URL, imageUrl);
        setResult(REQUEST_CODE, mIntent);
        // ページジャンプ
        mPageJumpFlag = true;
        finish();
    }

    public void rotateImage(View view) {
        Log.i(TAG, "ProfileClipActivity_rotateImage");
        Bitmap bitmap = imageView.getCroppedBitmap();
        // rotate by center point
        imageView.setPivotX(imageView.getWidth()/2);
        imageView.setPivotY(imageView.getHeight()/2);

        float currentRotation = imageView.getRotation()>=360?0:imageView.getRotation();
        imageView.setRotation(currentRotation + 90);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i(TAG, "ProfileClipActivity_onActivityResult");
        if (null == data) {
            setResult(REQUEST_CODE, mIntent);
            finish();
            return;
        } else if (resultCode != Activity.RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case 1:
                try {
                    Uri imageUri = data.getData();
                    Point screenSize = ImageUtils.getScreenSize(this);
                    Bitmap scaledBitmap = ImageUtils.decodeUriToScaledBitmap(this, imageUri, screenSize.x, screenSize.y);
                    imageView.setImageBitmap(scaledBitmap);

                } catch (Exception e) {

                }
                break;
            case  RequestCodeConstants.MIMAMORI_CONTACT_ADD:
                // Mimamori Add Contact
                mMimamoriBusinessService.onContactAddResult(true);
                break;
        }
    }

    /**
     * ページリターンキー、フルスクリーンリターンジェスチャー
     */
    @Override
    public void onBackPressed() {
        backActivity(null);
    }

    /**
     * 前のページに戻る(値なし)
     */
    public void backActivity(View view) {
        Log.i(TAG, "ProfileClipActivity_backActivity");
        // ページジャンプ
        mPageJumpFlag = true;
        ProfileClipActivity.this.finish();
    }
}
